<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\CreateStudent;
use App\Http\Requests\User\CreateTeacher;
use App\Http\Requests\User\EmailRequest;
use App\Models\SchoolLikeUsers;
use App\Models\SchoolRoles;
use App\Models\SchoolRoleUsers;
use App\Models\User;
use App\Repositories\Cache\RegisterCode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class ManagerController extends Controller
{
    /**
     * 新建学生
     *
     * @param CreateStudent $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createStudent(CreateStudent $request)
    {
        $name = $request->input('name');
        $password = $request->input('password');
        $email = $request->input('email');
        $schoolId = $request->input('school_id');
        // 创建用户
        $userData = [
            'name' => $name,
            'password' => bcrypt($password),
            'email' => $email,
        ];
        $user = User::create($userData);

        // 创建学生角色
        $roleUserData = [
            'user_id' => $user->id,
            'role_id' => SchoolRoles::STUDENT_ROLE,
            'school_id' => $schoolId,
        ];
        SchoolRoleUsers::create($roleUserData);

        return success();
    }

    /**
     * 邀请成为普通教师
     *
     * @param EmailRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function invite(EmailRequest $request)
    {
        $email = $request->input('email');
        $schoolId = $request->input('school_id');
        $url = $request->input('url');

        // 生成验证码缓存
        $registerCode = new RegisterCode();
        $code = rand6();
        $registerCode->setCodeCache($email, $code);

        // 发送邮件
        $subject = 'Welcome to Educational! Confirm Your Email';

        $params = [
            'link' => $url . '?email=' . urlencode($email) . '&code=' . $code,
            'linkName' => 'Click Here'
        ];
        Mail::send(
            'emails.teacher-verification',
            ['content' => $params],
            function ($message) use ($email, $subject) {
                $message->to($email)->subject($subject);
            }
        );

        return success();
    }

    /**
     * 创建普通教师
     *
     * @param CreateTeacher $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createTeacher(CreateTeacher $request)
    {
        $name = $request->input('name');
        $password = $request->input('password');
        $email = $request->input('email');
        $code = $request->input('code');
        $schoolId = $request->input('school_id');
        // todo school必须存在

        // 查询缓存中的验证码并进行验证
        $registerCode = new RegisterCode();
        $cacheCode = $registerCode->getCode($email);
        if (!$cacheCode) {
            return error("Not yet invited");
        }
        if ($cacheCode != $code) {
            return error("verification failed");
        }

        // 创建用户
        $userData = [
            'name' => $name,
            'password' => bcrypt($password),
            'email' => $email,
        ];
        $user = User::create($userData);

        // 创建老师角色
        $roleUserData = [
            'user_id' => $user->id,
            'role_id' => SchoolRoles::TEACHER_ROLE,
            'school_id' => $schoolId,
        ];
        SchoolRoleUsers::create($roleUserData);

        return success();
    }


    public function fansList()
    {
        $schoolIds = SchoolRoleUsers::where([
            'role_id' => SchoolRoles::MANAGER_ROLE,
            'user_id' => Auth::id(),
        ])->pluck('school_id');
        $data = SchoolLikeUsers::with('student', 'school')
            ->where('teacher_id', Auth::id())
            ->whereIn('school_id', $schoolIds)
            ->get();
        return success($data);
    }
}